package com.magicborrow.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.magicborrow.Constants;
import com.magicborrow.MagicBorrowApplication;
import com.magicborrow.R;
import com.magicborrow.beans.AddressBean;
import com.magicborrow.beans.BaseBean;
import com.magicborrow.beans.StuffBean;
import com.magicborrow.enums.PriceModeEnum;
import com.magicborrow.utils.StringTools;
import com.magicborrow.utils.StringUtil;
import com.magicborrow.utils.UserTools;
import com.magicborrow.utils.ViewPressedUtil;
import com.magicborrow.utils.VolleyTool;
import com.magicborrow.views.LoadingDialog;
import com.magicborrow.views.MsgDialog;
import com.magicborrow.views.SelectorTimeDialog;
import com.magicborrow.views.StudentDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class BorrowingActivity extends BaseActivity implements View.OnClickListener {

    private TextView stuffName;
    private TextView stuffOwner;
    private TextView stuffDeposit;
    private TextView stuffDepositDiscount;
    private TextView stuffRent;
    private TextView etDays;
    private TextView tvTotalAmount;
    private TextView tvAddressCheck;
    private StuffBean bean;
    private AddressBean address;
    private String number = "0";
    private LoadingDialog loadingDialog;
    private StudentDialog studentDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.borrowing_activity);
        bean = (StuffBean) getIntent().getSerializableExtra("data");

        stuffName = (TextView) findViewById(R.id.stuff_name);
        stuffOwner = (TextView) findViewById(R.id.stuff_owner);
        stuffDeposit = (TextView) findViewById(R.id.stuff_deposit);
        stuffDepositDiscount = (TextView) findViewById(R.id.stuff_deposit_discount);
        stuffRent = (TextView) findViewById(R.id.stuff_rent);
        etDays = (TextView) findViewById(R.id.et_days);
        tvTotalAmount = (TextView) findViewById(R.id.tv_totalAmount);
        tvAddressCheck = (TextView) findViewById(R.id.tv_address_check);
        stuffName.setText(bean.getName());
        stuffOwner.setText(bean.getUser().getNickname());
        stuffDeposit.setText("￥" + bean.getDeposit());
        stuffDepositDiscount.setText(setDepositRul(bean.getDeposit()));
        stuffRent.setText(bean.getPrice() + "/" + PriceModeEnum.getModeStr(bean.getPriceMode()));


        findViewById(R.id.btn_submit).setOnClickListener(this);
        tvAddressCheck.setOnClickListener(this);
        findViewById(R.id.btn_submit).setOnTouchListener(ViewPressedUtil.TouchPress);
        etDays.setOnClickListener(this);
        getEtPhone().setText(UserTools.getUser(this).getMobile());
    }

    private String setDepositRul(int deposit) {
        double depositRul = 0;
        String s;
        String p = null;
        if (deposit >= 100 && deposit < 1000) {
            depositRul = deposit * (1-7.0 / 10);
            p = "70%";
        } else if (deposit >= 1000 && deposit < 3000) {
            depositRul = deposit * (1-6.0 / 10);
            p = "60%";
        } else if (deposit >= 3000 && deposit < 10000) {
            depositRul = deposit * (1-7.0 / 10);
            p = "70%";
        } else if (deposit >= 10000 && deposit < 20000) {
            depositRul = deposit * (1-3.0 / 10);
            p = "30%";
        } else {
            depositRul = 0;
        }
        if (depositRul != 0) {
            s = "（您只需支付" + StringUtil.double2String(depositRul) + "元，平台为您垫付垫付" + p + "！平台将暂时为您保存，交易完成后返回到您的账户！）";
        } else {
            s = "";
        }
        return s;

    }

    private EditText getEtPhone() {
        return (EditText) findViewById(R.id.et_phone);
    }

    private EditText getTvAddress() {
        return (EditText) findViewById(R.id.tv_address);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_submit:
                if ("0".equals(number)) {
                    MsgDialog dialog = new MsgDialog(this, "您的租借数量需要大于0", null);
                    dialog.show();
                    return;
                }
                if (address == null || TextUtils.isEmpty(getTvAddress().getText().toString())) {
                    MsgDialog dialog = new MsgDialog(this, "请选择并填入正确的地址", null);
                    dialog.show();
                    return;
                }
                if (TextUtils.isEmpty(getEtPhone().getText().toString()) && getEtPhone().getText().toString().length() != 11) {
                    MsgDialog dialog = new MsgDialog(this, "请填入正确的联系电话", null);
                    dialog.show();
                    return;
                }
                HashMap<String, String> params = new HashMap<>();
                params.put("id", bean.getId() + "");
                params.put("acc_token", UserTools.getUser(this).getAcc_token());
                params.put("number", number);
                params.put("phone", getEtPhone().getText().toString());
                params.put("address", address.getAddress());
                params.put("addressDetail", address.getAddressInfo());
                params.put("lat", address.getLat() + "");
                params.put("lon", address.getLon() + "");
                loadingDialog = new LoadingDialog(this);
                loadingDialog.show();
                VolleyTool.post(Constants.URL_POST_I_BORROWING, params, new VolleyTool.HTTPListener() {
                    @Override
                    public <T> void onResponse(T t, int requestCode) {
                        loadingDialog.dismiss();
                        BaseBean bean = (BaseBean) t;
                        if (bean.getCode() >= 0) {
                            MsgDialog dialog = new MsgDialog(BorrowingActivity.this, "您的物品已经发给物主\n请耐心等候", null);
                            dialog.show();
                            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                                @Override
                                public void onDismiss(DialogInterface dialog) {
                                    finish();
                                }
                            });
                        } else {
                            if (bean.getCode() == -114) {//进行学生验证
                                showValidateDialog();
                            }
                            showShortMsg(bean.getMessage());
                        }
                    }

                    @Override
                    public void onErrorResponse(VolleyError error, int requestCode) {
                        loadingDialog.dismiss();

                    }
                }, 0, BaseBean.class);


                break;
            case R.id.tv_address_check:
                Intent intent = new Intent(this, AddressManagerActivity.class);
                startActivityForResult(intent, 1);
                break;
            case R.id.et_days:

                List<String> data2 = new ArrayList<>();
                data2.add(PriceModeEnum.getModeStr(bean.getPriceMode()));
                final SelectorTimeDialog timeDialog = new SelectorTimeDialog(this, data2);

                timeDialog.show();

                timeDialog.setOnOkClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        timeDialog.getCurrentPriceMode();
                        number = timeDialog.getTimeNumber();
                        //      Log.i("==9998==",""+timeDialog.getTimeNumber());
                        etDays.setText("" + timeDialog.getTimeNumber() + "/" + PriceModeEnum.getModeStr(bean.getPriceMode()));
                        tvTotalAmount.setText("￥" + Integer.valueOf(timeDialog.getTimeNumber()) * bean.getPrice());

                        timeDialog.dismiss();
                        //     Log.i("==9999==",""+timeDialog.getCurrentPriceMode());

                    }
                });
                break;
        }
    }

    private void showValidateDialog() {
        studentDialog = new StudentDialog(this);
        studentDialog.show();
        studentDialog.setOnClickValidete(new StudentDialog.OnClickValidete() {
            @Override
            public void clickValidate() {
                validate();//去验证
            }
        });
    }

    private void validate() {
        Intent intent = getIntent();
        intent.setClass(this, SchoolListActivity.class);
        startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            address = (AddressBean) data.getSerializableExtra("address");
            tvAddressCheck.setText(address.getAddress());
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (MagicBorrowApplication.getInstance().isPass()) {
            if (studentDialog != null) {
                studentDialog.dismiss();
            }
            MagicBorrowApplication.getInstance().setPass(false);
        }
    }
}
